from datetime import datetime

from flask import jsonify, g, current_app, request, json

from ihome_blue import ihome_blue
from init import db
from models import User, House, Area
from utils.commons import user_login_data
from utils.response_code import RET


@ihome_blue.route('/user')
@user_login_data
def users():
    # g.user.id = 7
    # if not g.user:
    #     return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")
    try:
        user = User.query.filter(User.id == 7).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not user:
        return jsonify(errno=RET.USERERR,errmsg="用户不存在或未激活")
    avatar_url = user.avatar_url
    mobile = user.mobile
    name = user.name

    data = {
        "avatar_url":avatar_url,
        "mobile":mobile,
        "name":name
    }

    return jsonify(errno=RET.OK,errmsg="0",data = data)

@ihome_blue.route('/user/name',methods = ["POST"])
@user_login_data
def user_name():
    try:
        user = User.query.filter(User.id == 7).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not user:
        return jsonify(errno=RET.USERERR,errmsg="用户不存在或未激活")
    name = request.json.get("name")

    if not name:
        return jsonify(errno=RET.NODATA,errmsg="无数据")

    user.name = name

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR,errmsg="写入数据库错误")

    return jsonify(errno=RET.OK,errmsg="OK")


@ihome_blue.route('/user/avatar', methods=["POST"])
@user_login_data
def user_avatar():
    try:
        user = User.query.filter(User.id == 7).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在或未激活")
    # 这部分可以修改
    content = request.files.get("avatar")
    with open("static/file","wb") as f:
        f.write(content.read())
    avatar_url = "/static/file"
    # 修改
    if not avatar_url:
        return jsonify(errno=RET.NODATA, errmsg="无数据")

    user.avatar_url = avatar_url

    try:
        db.session.add(user)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="写入数据库错误")
    data = {
        "avatar_url":avatar_url
    }

    return jsonify(errno=RET.OK, errmsg="OK",data = data)

# 获取或者设置用户实名信息
@ihome_blue.route('/user/auth', methods=["GET","POST"])
@user_login_data
def user_auth():
    try:
        user = User.query.filter(User.id == 7).first()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not user:
        return jsonify(errno=RET.USERERR, errmsg="用户不存在或未激活")
    if request.method == "GET":
        real_name = user.real_name
        id_card = user.id_card

        data = {
           "real_name":real_name,
            "id_card":id_card
        }

        return jsonify(errno=RET.OK, errmsg="0", data=data)
    else:
        real_name = request.json.get("real_name")
        id_card = request.json.get("id_card")

        if not all([real_name, id_card]):
            return jsonify(errno=RET.NODATA, errmsg="无数据")

        user.real_name = real_name
        user.id_card = id_card

        try:
            db.session.add(user)
            db.session.commit()
        except Exception as e:
            current_app.logger.error(e)
            return jsonify(errno=RET.DATAERR, errmsg="写入数据库错误")
        data = {
            "real_name": real_name,
            "id_card": id_card
        }

        return jsonify(errno=RET.OK, errmsg="OK", data=data)

# 获取房屋发布列表
@ihome_blue.route('/user/houses')
@user_login_data
def user_house():
    # g.user.id = 7
    # if not g.user:
    #     return jsonify(errno=RET.SESSIONERR,errmsg="用户未登录")
    try:
        # user = User.query.filter(User.id == 7).first()
        houses = House.query.filter(House.user_id == 7).orderby(House.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
    if not houses:
        return jsonify(errno=RET.DATAERR,errmsg="数据不存在")
    # houses = user.houses
    housetotal = []
    for house in houses:
        housetotal.append(house.to_basic_dict())
    data = {
        "house":housetotal
    }
    return jsonify(errno=RET.OK,errmsg="0",data = data)

# # 用户发布房源
# @ihome_blue.route('/houses',methods = ["POST"])
# @user_login_data
# def user_houses():
#     # try:
#         # user = User.query.filter(User.id == 7).first()
#     #     house = House.query.filter().first()
#     # except Exception as e:
#     #     current_app.logger.error(e)
#     #     return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")
#     house = House()
#     house.title = request.json.get("title")
#     house.price = request.json.get("price")
#     house.area_id = request.json.get("area_id")
#     house.address = request.json.get("address")
#     house.room_count = request.json.get("room_count")
#     house.acreage = request.json.get("acreage")
#     house.unit = request.json.get("unit")
#     house.capacity = request.json.get("capacity")
#     house.beds = request.json.get("beds")
#     house.deposit = request.json.get("deposit")
#     house.min_days = request.json.get("min_days")
#     house.max_days = request.json.get("max_days")
#     house.facilities = request.json.get("facility")
#     house.create_time = datetime.now()
#     house.user_id = 7
#     # user.houses.append(house)
#
#     if not all([house.title,house.price,house.area_id,house.address,
#                 house.room_count,house.acreage,
#                 house.unit,house.capacity,house.beds,
#                 house.deposit,house.min_days,
#                 house.max_days,house.facilities]):
#         return jsonify(errno=RET.PARAMERR,errmsg="参数不全")
#
#     try:
#         db.session.add(house)
#         db.session.commit()
#     except Exception as e:
#         current_app.logger.error(e)
#         return jsonify(errno=RET.DATAERR,errmsg="写入数据库错误")
#     data = {
#         "house_id":1
#     }
#
#     return jsonify(errno=RET.OK,errmsg="OK",data = data)


# 获取发布页面的地区下拉菜单内容显示
@ihome_blue.route('/areas')
@user_login_data
def users_areas():
    try:
        area = Area.query.all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库查询错误")

    areas = []
    for area_ in area:
        areas.append(area_.to_dict())
    # areas = json.dumps(areas)
    return jsonify(errno=RET.OK, errmsg="0", data=areas)








